<template>
	<view class="page" v-if="dataTree">
		<view class="input_area">
			<u--form :model="model" ref="form" errorType="message" labelWidth="auto"
				:labelStyle="{ padding: '5px 30px 5px 0',fontWeight : '600', fontSize : '15px' }">
				<u-form-item prop="name" :borderBottom="true" label="您的姓名">
					<u--input v-model="model.name" border="none" clearable placeholder="请输入您的姓名"
						placeholderClass="pricePlaceholder">
					</u--input>
				</u-form-item>
				<u-form-item prop="tel" :borderBottom="true" label="手机号码">
					<u--input v-model="model.tel" type="number" border="none" clearable placeholder="请输入手机号码"
						maxlength="11" placeholderClass="pricePlaceholder">
					</u--input>
				</u-form-item>
				<u-form-item prop="fieldArea" @click="openMapPicker" :borderBottom="true" label="所在地区">
					<uni-data-picker placeholder="请选择所在地区" popup-title="请选择所在地区" :localdata="dataTree" v-model="classes"
						:map="{text:'label',value:'field'}" @change="fieldAreaConfirm" :clear-icon="false">
					</uni-data-picker>
				</u-form-item>
				<u-form-item prop="detailAddress" label="详细地址">
					<u--input v-model="model.detailAddress" border="none" clearable placeholder="请输入您的详细地址"
						placeholderClass="pricePlaceholder">
					</u--input>
				</u-form-item>
			</u--form>
		</view>
	</view>
	<fixed-button @touch="submit">提交</fixed-button>
</template>

<script setup>
	import { onLoad } from '@dcloudio/uni-app';
	import { nextTick, reactive, ref, onMounted } from 'vue';
	import request from '@/utils/common/request/index';
	import { sleep } from '@/utils/common/index';
	import { useGetThemColor } from '@/hooks/useGetThemColor';

	const { secondaryColor } = useGetThemColor();
	let addressId = '';
	onLoad(async option => {
		await getAllData();
		if (option.id) {
			addressId = option.id;
			getDetail(addressId);
		}
		uni.setNavigationBarTitle({
			title: addressId ? '修改地址' : '添加地址'
		});
	});

	const dataTree = ref(null);
	let classes = ref('null');
	// * 获取省市区数据
	const getAllData = () => {
		return request({
			url: '/api/qrallciry',
			loadingTip: '加载中'
		}).then(res => {
			res = res.filter(item => {
				return item.children;
			});
			res.forEach((item, index) => {
				item.field = (index + 1) + '-0-0';
				if (!item.children) item.children = [];
				item.children.forEach((secondItem, secondIndex) => {
					secondItem.field = (index + 1) + '-' + (secondIndex + 1);
					if (!secondItem.children) secondItem.children = [];
					secondItem.children.forEach((thirdItem, thirdIndex) => {
						thirdItem.field = index + 1 + '-' + (secondIndex + 1) + '-' +
							(thirdIndex + 1);
					})
				})
			})
			dataTree.value = res;
		})
	};

	// * 表单数据
	const form = ref(null);
	let model = reactive({
		name: '',
		tel: '',
		fieldArea: '',
		detailAddress: '',
	});
	// * 校验规则
	const rules = {
		name: [{
				required: true,
				message: '请输入您的姓名',
				trigger: ['blur', 'change'],
			},
			{
				validator: (rule, value, callback) => {
					return value.trim() !== '';
				},
				message: '姓名格式错误',
			},
		],
		tel: [{
				required: true,
				message: '请输入电话号码',
				trigger: ['blur', 'change'],
			},
			{
				validator: (rule, value, callback) => {
					return uni.$u.test.mobile(value);
				},
				message: '电话号码格式错误',
			},
		],
		fieldArea: [{
			required: true,
			message: '请选择地区',
			trigger: ['blur', 'change'],
		}, ],
		detailAddress: [{
			required: true,
			message: '请输入详细地址',
			trigger: ['blur', 'change'],
		}, ],
	};

	const setFormRules = () => {
		if (!form.value) {
			setTimeout(() => {
				setFormRules();
			}, 200)
		} else {
			form.value.setRules(rules);
		}
	}

	onMounted(() => {
		setFormRules();
	});

	const fieldAreaConfirm = (e) => {
		model.fieldArea = classes.value;
		form.value.validate()
	};


	// * 提交
	const submit = () => {
		form.value.validate().then(() => {
			// * 匹配出省市区code
			const indexs = classes.value.split('-');
			const province = dataTree.value[indexs[0] - 1];
			const city = province.children[indexs[1] - 1];
			const area = (city.children && indexs.length > 2) ? city.children[indexs[2] - 1] : undefined;

			let reqData = {
				name: model.name,
				tel: model.tel,
				address: model.detailAddress,
				province_code: province.value,
				city_code: city.value
			}

			if (area) {
				reqData.area_code = area.value;
			} else {
				reqData.area_code = city.value;
			}

			if (addressId) reqData.address_id = addressId;
			request({
				url: addressId ? '/api/editaddress' : '/api/createaddress',
				method: 'POST',
				loadingTip: '处理中',
				data: reqData
			}).then(async () => {
				uni.showToast({
					title: addressId ? '修改成功' : '添加成功',
					icon: 'success',
				});
				await sleep();
				uni.navigateBack();
			})

		}).catch(err => {})
	}

	// * 根据id获取地址信息
	const getDetail = (id) => {
		request({
			url: '/api/addressdetail',
			loadingTip: '加载中',
			data: {
				address_id: id
			}
		}).then(addressInfo => {
			model.name = addressInfo.name;
			model.tel = addressInfo.tel;
			model.detailAddress = addressInfo.address;

			// * 匹配出省市区
			const provinceIndex = dataTree.value.findIndex(item => {
				return item.value == addressInfo.province_code;
			})
			const cityIndex = dataTree.value[provinceIndex].children.findIndex(item => {
				return item.value == addressInfo.city_code;
			})
			const areaIndex = dataTree.value[provinceIndex].children[cityIndex].children.findIndex(item => {
				return item.value == addressInfo.area_code;
			})

			let classesValue
			if (areaIndex === -1) { //没有区县
				classesValue = (provinceIndex + 1) + '-' + (cityIndex + 1);
			} else {
				classesValue = (provinceIndex + 1) + '-' + (cityIndex + 1) + '-' + (areaIndex + 1);
			}

			model.fieldArea = classesValue;
			classes.value = classesValue;
		})
	};
</script>

<style lang="scss" scoped>
	.input_area {
		padding: 20rpx;
		background-color: #fff;
		border-radius: 20rpx;
		overflow: hidden;

		::v-deep .uni-data-pickerview .selected-item-active,
		::v-deep .uni-data-pickerview .check {
			border-color: v-bind(secondaryColor);
		}

		::v-deep .input-value {
			padding: 0 !important;
			border: none !important;
		}

		::v-deep .selected-area.placeholder {
			font-size: 14px !important;
			color: rgb(192, 196, 204) !important;
		}

		::v-deep .u-form-item__body__right__message {
			margin-left: 95px !important;
		}
	}
</style>
<style>
	page {
		background-color: #f5f5f5;
	}
</style>